package commondata

import (
	"fmt"
	"sync"
	"usplatformserver/global"
	"usplatformserver/internal/service"

	cmap "github.com/orcaman/concurrent-map"
)

type commonData struct {
	WaitDownloadCounts cmap.ConcurrentMap
	//Lock               sync.Mutex
}

var (
	instance *commonData
	once     sync.Once
)

func New() *commonData {
	once.Do(func() {
		instance = &commonData{
			WaitDownloadCounts: cmap.New(),
		}
	})
	return instance
}

/**
 * @brief 获取待下载文件个数
 * @param organType-检查部位
 */
func (s *commonData) GetWaitDownloadCount(organType int) int {
	var count int = 0

	if v, ok := s.WaitDownloadCounts.Get(fmt.Sprintf("%d", organType)); ok {
		count = v.(int)
	}
	return count
}

/**
 * @brief 初始化待下载文件个数
 * @return 待下载文件个数，错误信息
 */
func (s *commonData) InitWaitDownloadCount() {
	counts, err := service.InitWaitDownloadCount()
	if err != nil {
		global.Logger.Infof("InitWaitDownloadCount failed: %v", err)
		return
	}
	for k, v := range counts {
		s.WaitDownloadCounts.Set(fmt.Sprintf("%d", k), v)
	}
	fmt.Println(s.WaitDownloadCounts)
}

/**
 * @brief 更新待下载文件个数
 * @param organType-检查部位
 */
func (s *commonData) UpdateWaitDownloadCount(organType int) {
	count, err := service.GetWaitDownloadCount(organType)
	if err != nil {
		global.Logger.Infof("GetWaitDownloadCount failed: %v", err)
		return
	}

	sKey := fmt.Sprintf("%d", organType)
	s.WaitDownloadCounts.Set(sKey, count)
}

/**
 * @brief 待下载文件个数+1
 * @param organType-检查部位
 */
func (s *commonData) AddWaitDownloadCount(organType int) {
	sKey := fmt.Sprintf("%d", organType)
	v, ok := s.WaitDownloadCounts.Get(sKey)
	if ok {
		count := v.(int)
		s.WaitDownloadCounts.Set(sKey, count+1)
	} else {
		s.WaitDownloadCounts.Set(sKey, 1)
	}
	fmt.Println(s.WaitDownloadCounts)
}

/**
 * @brief 待下载文件个数-1
 * @param organType-检查部位
 */
func (s *commonData) SubstractWaitDownloadCount(organType int) {
	sKey := fmt.Sprintf("%d", organType)
	v, ok := s.WaitDownloadCounts.Get(sKey)
	if ok {
		count := v.(int)
		s.WaitDownloadCounts.Set(sKey, count-1)
	}
}
